package org.example.controller;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import okhttp3.RequestBody;
import org.example.pojo.ChatRequest;
import org.example.pojo.ChatResponse;
import org.example.pojo.Result;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.*;

import javax.annotation.PostConstruct;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/deepseek")
@Slf4j
public class DeepSeekController {

    private OkHttpClient client;

    @PostConstruct
    public void init() {
        log.info("初始化DeepSeek HTTP客户端...");
        // 创建OkHttpClient实例，项⽬启动时就初始化
        client = new OkHttpClient
                .Builder()
                .connectTimeout(120, TimeUnit.SECONDS)
                .writeTimeout(120, TimeUnit.SECONDS)
                .readTimeout(120, TimeUnit.SECONDS)
                .connectionPool(new ConnectionPool(5, 5, TimeUnit.MINUTES))
                .build();
        log.info("DeepSeek HTTP客户端初始化完成");
    }

    @GetMapping("/prompt")
//    @Anonymous
    public Result DeepSeekAPI(String prompt) {
        // 构建 JSON 请求体
        ChatRequest chatRequest = new ChatRequest();
        chatRequest.setStream(false);
        chatRequest.setModel("deepseek-r1:1.5b");
        chatRequest.setPrompt(prompt);
        String jsonString = JSON.toJSONString(chatRequest);
        MediaType jsonType = MediaType.get("application/json; charset=utf8");

        RequestBody body = RequestBody.create(jsonType, jsonString);
        // 创建 POST 请求
        Request request = new Request.Builder()
                .url("http://localhost:11434/api/generate")
                .addHeader("Content-Type", "application/json")
                .post(body)
                .build();
        // 发送同步 POST 请求
        try (Response response = client.newCall(request).execute()) {
            if (response.isSuccessful()) {
                ChatResponse chatResponse = JSON.parseObject(response.body
                        ().string(), ChatResponse.class);
                String responseString = chatResponse.getResponse();
                // 使⽤ StringBuilder 去掉 <think> 标签及其之间的内容，并去掉换
                StringBuilder result = new StringBuilder();
                boolean inThinkTag = false;
                for (int i = 0; i < responseString.length(); i++) {
                    char c = responseString.charAt(i);
                    if (c == '<') {
                        if (responseString.startsWith("<think>", i)) {
                            inThinkTag = true;
                            i += 6; // 跳过 "<think>"
                        } else if (responseString.startsWith("</think>", i
                        )) {
                            inThinkTag = false;
                            i += 7; // 跳过 "</think>"
                        }
                    }
                    if (!inThinkTag && c != '\n' && c != '\r') {
                        result.append(c);
                    }
                }
                responseString = result.toString();
                responseString = responseString.substring(1);
                log.info("responseString:"+responseString);
                return Result.success(responseString);
            } else {
                throw new RuntimeException("DeepSeek服务器响应异常");
            }
        } catch (IOException e) {

            throw new RuntimeException("DeepSeek服务器连接异常");
        }
    }


}
